<?php

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use app\admin\model\AuthRule;
use think\Controller;
use think\Db;
/**
 *
 * 角色管理
 * @author fenghao <303529990@qq.com>
 */
class Menu extends Base
{

    /**
     * 获取角色列表
     * @return type
     */
    public function lists()
    {
        if(request()->isAjax()){
            if(!isset($this->_map['pid']))$this->_map['pid'] = 0;
            //print_r($this->_map);die;
            $lists = AuthRule::where($this->_map)->order($this->_order)->select();

            $this->ajaxReturn('',$lists,count($lists));
        }else{
            $lists = AuthRule::where($this->_map)->where('pid',0)->order($this->_order)->select();
            foreach ($lists as $k=>$v){
                $son = AuthRule::where('pid',$v['id'])->order('sort')->select();
                if(!empty($son)){
                    foreach ($son as $ka=>$va){
                        $son[$ka]['son'] = AuthRule::where('pid',$va['id'])->order('sort')->select();
                    }
                }
                $lists[$k]['son'] = $son;
            }
            $this->assign('parents_menu', json_encode($lists));
            $this->assign('lists', $lists);
            return $this->fetch();
        }
    }

    //添加角色
    public function add()
    {

        return $this->_edit();
    }

    /**
     * 修改角色
     * @return type
     */
    public function edit($id)
    {
        return $this->_edit($id);
    }

    private function _edit($id = '')
    {
        if ($this->request->isPost()) {
            //print_r($id);die;
            $rule = [
                ['title', 'require|length:1,32', '栏目名称不能为空|栏目名称必须在1~32个字符之间'],
                ['name', 'require', '栏目标识不能为空'],
            ];
            $msg = $this->validate($this->_param, $rule);
            if ($msg !== true) {
                $this->error($msg, '');
            }
            if(empty($id)){
                $re = AuthRule::insert($this->_param);
            }else{
                $re = AuthRule::where('id',$id)->update($this->_param);
            }
            $re?$this->ajaxReturn('操作成功'):$this->ajaxReturn('操作失败');
        }
    }


    //批量删除用户
    public function del($id='')
    {
        if(empty($id))$this->ajaxReturn('操作失败');
        $id = is_array($id)?$id:[$id];
        $ids = $this->all_menu($id,$id);
        $re = Db::name('auth_rule')->where("id",'in',$ids)->delete();
        $re?$this->ajaxReturn('操作成功'):$this->ajaxReturn('操作失败');
    }
    public function all_menu($id,$ids = []){
        $son = Db::name('auth_rule')->where("pid",'in',$id)->select();
        if(!empty($son)){
            $ids0 = array_column($son, 'id');$ids = array_merge($id,$ids0);
            return $this->all_menu($ids0,$ids);
        }
        return $ids;
    }
}
